﻿using AntdUI;
using CKS.PLC.Core.Cache;
using CKS.PLC.Core.Event;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.DataCollection.Helper;


namespace CKS.MES.Server
{
    public partial class MainForm2 : AntdUI.Window
    {
        public MainForm2()
        {
            InitializeComponent();
            //AntdUI.Config.Mode = AntdUI.TMode.Dark;
            //AntdUI.Config.IsDark = true;

            txtLog.ReadOnly = true;
            this.FormClosing += MainForm2_FormClosing;
            this.Load += MainForm2_Load;
            this.Text = "KS@MesServer";
            txtLog.AutoScroll = true;

        }

        

        private void MainForm2_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = AntdUI.Modal.open(new AntdUI.Modal.Config(this, "Message",
                  "Are you sure to exit")
            {
                //禁止使用键盘关闭
                Keyboard = false,
                MaskClosable = false,
                OkText = "Yes",
                CancelText = "No",
            });
            if (dr != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }
        public string backendUrl = "";

        private void MainForm2_Load(object sender, EventArgs e)
        {
            AddLog("启动成功！");

            var ipAll = ToolsHelper.GetLocalIps();
            foreach (var item in ipAll)
            {
                AddLog($"本地IP {item}");
            }


            var app = InternalApp.App;
            var url = app.Urls.First();
            var u = new Uri(url);


         //   pnlLeft.Width = 0;
            this.Icon = ImageToIcon(pageHeader1.Icon);
            
            this.StartPosition = FormStartPosition.CenterScreen;
            backendUrl = $"{u.Scheme}://localhost:{u.Port}/";
            AddLog($"本机服务地址:{backendUrl}");
            //if(!localIP.IsEmpty())
            //    AddLog($"局域网服务地址:{u.Scheme}://{localIP}:{u.Port}/");
            foreach (var localIP in ipAll)
            {
                AddLog($"局域网服务地址:{u.Scheme}://{localIP}:{u.Port}/");

            }
            txtLog.TabStop = false;
            txtLog.BorderActive = Color.Transparent;
            txtLog.BorderHover = Color.Transparent;
            IntervalWriteLog();
            Task.Run(UpdatePlcTable);
        }



        public Icon ImageToIcon(Image image)
        {
            // 创建一个与原始图像大小相同的空白图像
            Bitmap iconBitmap = new Bitmap(64, 64);
            // 使用原始图像绘制空白图像
            using (Graphics graphics = Graphics.FromImage(iconBitmap))
            {
                graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.DrawImage(image, 0, 0, 64, 64);
            }
            using (Icon icon = Icon.FromHandle(iconBitmap.GetHicon()))
            {
                // 保存图标到文件
                //using (FileStream fs = new FileStream("output.ico", FileMode.Create, FileAccess.Write))
                //{
                //    icon.Save(fs);
                //}
                // 复制Icon，因为GetHicon()在调用后会释放图标资源
                return Icon.FromHandle(icon.Handle);
            }

        }

        private void btnVisit_Click(object sender, EventArgs e)
        {
            if (!backendUrl.IsEmpty())
                System.Diagnostics.Process.Start(new ProcessStartInfo(backendUrl) { UseShellExecute = true });
        }


       
        private void AddLog(string msg)
        {

            EventBus.AddLog(msg);

        }

        private void IntervalWriteLog()
        {
            Task.Run(() =>
            {

                try
                {
                    int logPageSize = 50;
                    while (this.IsHandleCreated)
                    {
                        
                        List<string> logs = new List<string>();
                        while (EventBus.logQueues.TryDequeue(out string msg))
                        {
                            logs.Add(msg);
                        }

                        if (logs.Count > 0)
                        {
                            var lines = txtLog.Text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            if (logs.Count > 0)
                            {
                                foreach (string log in logs)
                                {
                                    //txtLog.AppendText(log);
                                    lines.Add(log);
                                }
                            }

                            if (lines.Count > logPageSize)
                            {
                                var newlines = lines.ToArray().Reverse().Take(logPageSize).Reverse();
                                txtLog.Text = string.Join("\r\n", newlines);
                            }
                            else
                            {
                                txtLog.Text = string.Join("\r\n", lines);
                                txtLog.ScrollToEnd();
                            }
                        }



                        Thread.Sleep(500);
                    }
                }
                catch (Exception)
                {

                }

            });

        }
        private async Task UpdatePlcTable()
        {
            try
            {
                while (this.IsHandleCreated)
                {
                    //获取客户端列表，绑定到UI
                    //在线状态，和心跳值。 心跳值是1 绿色，0 是黑色
                    var plcs = ServiceCommon.PlcClients.ToList().OrderBy(a=>a.PlcInfo.Id).ToList();

                    plcTable.BindPlc(plcs);
                    await Task.Delay(800);
                    
                }
            }
            catch (Exception)
            {

            }
        }

    }
}
